// 图片分享工具类
class ImageShare {
  constructor() {
    this.canvas = null
    this.ctx = null
  }

  // 初始化画布
  async initCanvas(width = 750, height = 1334) {
    return new Promise((resolve, reject) => {
      try {
        const query = uni.createSelectorQuery()
        query.select('#share-canvas').fields({
          node: true,
          size: true
        }).exec((res) => {
          if (res[0]) {
            const canvas = res[0].node
            const ctx = canvas.getContext('2d')
            
            const dpr = uni.getSystemInfoSync().pixelRatio
            canvas.width = width * dpr
            canvas.height = height * dpr
            ctx.scale(dpr, dpr)
            
            this.canvas = canvas
            this.ctx = ctx
            resolve({ canvas, ctx })
          } else {
            reject(new Error('Canvas not found'))
          }
        })
      } catch (e) {
        reject(e)
      }
    })
  }

  // 绘制渐变背景
  drawGradientBackground(colors = ['#667eea', '#764ba2']) {
    const gradient = this.ctx.createLinearGradient(0, 0, 0, this.canvas.height)
    colors.forEach((color, index) => {
      gradient.addColorStop(index / (colors.length - 1), color)
    })
    
    this.ctx.fillStyle = gradient
    this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height)
  }

  // 绘制文本
  drawText(text, x, y, options = {}) {
    const {
      fontSize = 28,
      color = '#000000',
      fontWeight = 'normal',
      textAlign = 'left',
      maxWidth = null,
      lineHeight = 1.4,
      fontFamily = 'PingFang SC, sans-serif'
    } = options

    this.ctx.font = `${fontWeight} ${fontSize}px ${fontFamily}`
    this.ctx.fillStyle = color
    this.ctx.textAlign = textAlign

    if (maxWidth) {
      const lines = this.wrapText(text, maxWidth)
      let totalHeight = 0
      
      lines.forEach((line, index) => {
        const lineY = y + (index * fontSize * lineHeight)
        this.ctx.fillText(line, x, lineY)
        totalHeight = (index + 1) * fontSize * lineHeight
      })
      
      return totalHeight
    } else {
      this.ctx.fillText(text, x, y)
      return fontSize * lineHeight
    }
  }

  // 文本换行处理
  wrapText(text, maxWidth) {
    const words = text.split('')
    const lines = []
    let currentLine = ''

    for (let i = 0; i < words.length; i++) {
      const testLine = currentLine + words[i]
      const metrics = this.ctx.measureText(testLine)
      
      if (metrics.width > maxWidth && currentLine !== '') {
        lines.push(currentLine)
        currentLine = words[i]
      } else {
        currentLine = testLine
      }
    }
    
    if (currentLine) {
      lines.push(currentLine)
    }
    
    return lines
  }

  // 绘制圆角矩形
  drawRoundedRect(x, y, width, height, radius, options = {}) {
    const { fillColor = '#ffffff', strokeColor = null, lineWidth = 1 } = options

    this.ctx.beginPath()
    this.ctx.moveTo(x + radius, y)
    this.ctx.lineTo(x + width - radius, y)
    this.ctx.quadraticCurveTo(x + width, y, x + width, y + radius)
    this.ctx.lineTo(x + width, y + height - radius)
    this.ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height)
    this.ctx.lineTo(x + radius, y + height)
    this.ctx.quadraticCurveTo(x, y + height, x, y + height - radius)
    this.ctx.lineTo(x, y + radius)
    this.ctx.quadraticCurveTo(x, y, x + radius, y)
    this.ctx.closePath()

    if (fillColor) {
      this.ctx.fillStyle = fillColor
      this.ctx.fill()
    }

    if (strokeColor) {
      this.ctx.strokeStyle = strokeColor
      this.ctx.lineWidth = lineWidth
      this.ctx.stroke()
    }
  }

  // 绘制圆形
  drawCircle(x, y, radius, options = {}) {
    const { fillColor = '#ffffff', strokeColor = null, lineWidth = 1 } = options

    this.ctx.beginPath()
    this.ctx.arc(x, y, radius, 0, 2 * Math.PI)

    if (fillColor) {
      this.ctx.fillStyle = fillColor
      this.ctx.fill()
    }

    if (strokeColor) {
      this.ctx.strokeStyle = strokeColor
      this.ctx.lineWidth = lineWidth
      this.ctx.stroke()
    }
  }

  // 绘制图标（使用emoji或简单图形）
  drawIcon(icon, x, y, size = 40) {
    this.ctx.font = `${size}px Arial`
    this.ctx.textAlign = 'center'
    this.ctx.fillText(icon, x, y + size / 3)
  }

  // 绘制统计卡片
  drawStatsCard(stats, x, y, width, height) {
    // 绘制卡片背景
    this.drawRoundedRect(x, y, width, height, 20, {
      fillColor: 'rgba(255, 255, 255, 0.9)',
      strokeColor: 'rgba(255, 255, 255, 0.3)',
      lineWidth: 1
    })

    const cardPadding = 30
    const itemHeight = (height - cardPadding * 2) / stats.length
    
    stats.forEach((stat, index) => {
      const itemY = y + cardPadding + index * itemHeight
      
      // 绘制图标
      this.drawIcon(stat.icon, x + 60, itemY + itemHeight / 2, 32)
      
      // 绘制标题
      this.drawText(stat.label, x + 100, itemY + itemHeight / 2 - 10, {
        fontSize: 24,
        color: '#666666',
        fontWeight: '500'
      })
      
      // 绘制数值
      this.drawText(stat.value, x + width - 50, itemY + itemHeight / 2 + 5, {
        fontSize: 28,
        color: '#333333',
        fontWeight: 'bold',
        textAlign: 'right'
      })
    })
  }

  // 绘制情绪趋势图
  drawMoodTrendChart(data, x, y, width, height) {
    if (!data || data.length === 0) return

    // 绘制图表背景
    this.drawRoundedRect(x, y, width, height, 15, {
      fillColor: 'rgba(255, 255, 255, 0.9)'
    })

    const padding = 40
    const chartX = x + padding
    const chartY = y + padding
    const chartWidth = width - padding * 2
    const chartHeight = height - padding * 2

    // 绘制标题
    this.drawText('情绪趋势', x + width / 2, y + 30, {
      fontSize: 24,
      fontWeight: 'bold',
      color: '#333333',
      textAlign: 'center'
    })

    // 绘制网格线
    const gridLines = 5
    for (let i = 0; i <= gridLines; i++) {
      const gridY = chartY + (i / gridLines) * chartHeight
      this.ctx.strokeStyle = 'rgba(200, 200, 200, 0.3)'
      this.ctx.lineWidth = 1
      this.ctx.beginPath()
      this.ctx.moveTo(chartX, gridY)
      this.ctx.lineTo(chartX + chartWidth, gridY)
      this.ctx.stroke()
    }

    // 绘制折线图
    if (data.length > 1) {
      const maxValue = Math.max(...data.map(d => d.value))
      const minValue = Math.min(...data.map(d => d.value))
      const valueRange = maxValue - minValue || 1

      this.ctx.strokeStyle = '#667eea'
      this.ctx.lineWidth = 3
      this.ctx.beginPath()

      data.forEach((point, index) => {
        const pointX = chartX + (index / (data.length - 1)) * chartWidth
        const pointY = chartY + chartHeight - ((point.value - minValue) / valueRange) * chartHeight

        if (index === 0) {
          this.ctx.moveTo(pointX, pointY)
        } else {
          this.ctx.lineTo(pointX, pointY)
        }

        // 绘制数据点
        this.drawCircle(pointX, pointY, 6, {
          fillColor: '#667eea',
          strokeColor: '#ffffff',
          lineWidth: 2
        })
      })

      this.ctx.stroke()
    }
  }

  // 生成情绪统计分享图
  async generateMoodStatsImage(data) {
    try {
      await this.initCanvas(750, 1334)

      // 绘制渐变背景
      this.drawGradientBackground(['#667eea', '#764ba2'])

      // 绘制标题区域
      const titleY = 120
      this.drawText('情绪大师', 375, titleY, {
        fontSize: 48,
        fontWeight: 'bold',
        color: '#ffffff',
        textAlign: 'center'
      })

      this.drawText('我的情绪统计报告', 375, titleY + 60, {
        fontSize: 28,
        color: 'rgba(255, 255, 255, 0.9)',
        textAlign: 'center'
      })

      // 绘制日期
      const reportDate = new Date().toLocaleDateString('zh-CN')
      this.drawText(reportDate, 375, titleY + 100, {
        fontSize: 20,
        color: 'rgba(255, 255, 255, 0.8)',
        textAlign: 'center'
      })

      // 绘制统计卡片
      const statsData = [
        { icon: '📅', label: '使用天数', value: `${data.usageDays}天` },
        { icon: '💭', label: '情绪记录', value: `${data.moodRecords}条` },
        { icon: '📊', label: '心理测评', value: `${data.testCount}次` },
        { icon: '🎧', label: '课程学习', value: `${data.courseCount}次` }
      ]

      this.drawStatsCard(statsData, 50, 300, 650, 280)

      // 绘制情绪趋势图
      if (data.moodTrend && data.moodTrend.length > 0) {
        this.drawMoodTrendChart(data.moodTrend, 50, 620, 650, 300)
      }

      // 绘制底部信息
      const bottomY = 1200
      this.drawText('坚持记录情绪，遇见更好的自己', 375, bottomY, {
        fontSize: 24,
        color: 'rgba(255, 255, 255, 0.9)',
        textAlign: 'center',
        fontWeight: '500'
      })

      // 绘制小程序码区域（占位）
      this.drawRoundedRect(320, bottomY + 40, 110, 110, 10, {
        fillColor: 'rgba(255, 255, 255, 0.9)'
      })

      this.drawText('扫码体验', 375, bottomY + 100, {
        fontSize: 16,
        color: '#666666',
        textAlign: 'center'
      })

      return await this.saveImage()

    } catch (error) {
      console.error('生成分享图失败:', error)
      throw error
    }
  }

  // 生成情绪记录分享图
  async generateMoodRecordImage(record) {
    try {
      await this.initCanvas(750, 1000)

      // 绘制渐变背景
      const moodColors = this.getMoodColors(record.mood)
      this.drawGradientBackground(moodColors)

      // 绘制主要内容区域
      this.drawRoundedRect(50, 150, 650, 700, 30, {
        fillColor: 'rgba(255, 255, 255, 0.95)'
      })

      // 绘制心情emoji
      const moodEmoji = this.getMoodEmoji(record.mood)
      this.drawText(moodEmoji, 375, 250, {
        fontSize: 120,
        textAlign: 'center'
      })

      // 绘制心情描述
      const moodText = this.getMoodText(record.mood)
      this.drawText(moodText, 375, 350, {
        fontSize: 36,
        fontWeight: 'bold',
        color: '#333333',
        textAlign: 'center'
      })

      // 绘制情绪强度
      this.drawText(`情绪强度: ${record.intensity}/10`, 375, 400, {
        fontSize: 24,
        color: '#666666',
        textAlign: 'center'
      })

      // 绘制日期时间
      const date = new Date(record.date)
      const dateStr = date.toLocaleDateString('zh-CN')
      const timeStr = date.toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit' 
      })
      
      this.drawText(`${dateStr} ${timeStr}`, 375, 450, {
        fontSize: 20,
        color: '#999999',
        textAlign: 'center'
      })

      // 绘制标签
      if (record.tags && record.tags.length > 0) {
        const tagsY = 520
        this.drawText('情绪标签', 375, tagsY, {
          fontSize: 24,
          fontWeight: 'bold',
          color: '#333333',
          textAlign: 'center'
        })

        const tagStartY = tagsY + 40
        record.tags.forEach((tag, index) => {
          const tagX = 375 - (record.tags.length * 60) / 2 + index * 120
          
          this.drawRoundedRect(tagX - 40, tagStartY - 15, 80, 30, 15, {
            fillColor: moodColors[0],
            strokeColor: 'rgba(255, 255, 255, 0.5)'
          })
          
          this.drawText(tag, tagX, tagStartY, {
            fontSize: 16,
            color: '#ffffff',
            textAlign: 'center'
          })
        })
      }

      // 绘制备注
      if (record.note) {
        const noteY = 650
        this.drawText('心情记录', 375, noteY, {
          fontSize: 24,
          fontWeight: 'bold',
          color: '#333333',
          textAlign: 'center'
        })

        this.drawText(record.note, 375, noteY + 40, {
          fontSize: 20,
          color: '#666666',
          textAlign: 'center',
          maxWidth: 550
        })
      }

      // 绘制底部标识
      this.drawText('情绪大师 - 记录每一份心情', 375, 920, {
        fontSize: 18,
        color: 'rgba(255, 255, 255, 0.8)',
        textAlign: 'center'
      })

      return await this.saveImage()

    } catch (error) {
      console.error('生成情绪记录分享图失败:', error)
      throw error
    }
  }

  // 获取心情对应的颜色
  getMoodColors(mood) {
    const colorMap = {
      1: ['#ff6b6b', '#ee5a52'], // 很难过 - 红色
      2: ['#ffa726', '#ff9800'], // 难过 - 橙色
      3: ['#66bb6a', '#4caf50'], // 一般 - 绿色
      4: ['#42a5f5', '#2196f3'], // 开心 - 蓝色
      5: ['#ab47bc', '#9c27b0']  // 很开心 - 紫色
    }
    return colorMap[mood] || ['#667eea', '#764ba2']
  }

  // 获取心情emoji
  getMoodEmoji(mood) {
    const emojiMap = {
      1: '😢',
      2: '😔',
      3: '😐',
      4: '😊',
      5: '😄'
    }
    return emojiMap[mood] || '😐'
  }

  // 获取心情文本
  getMoodText(mood) {
    const textMap = {
      1: '很难过',
      2: '难过',
      3: '一般',
      4: '开心',
      5: '很开心'
    }
    return textMap[mood] || '一般'
  }

  // 保存图片
  async saveImage() {
    return new Promise((resolve, reject) => {
      try {
        this.canvas.toTempFilePath({
          fileType: 'png',
          quality: 1,
          success: (res) => {
            resolve(res.tempFilePath)
          },
          fail: (error) => {
            reject(error)
          }
        })
      } catch (error) {
        reject(error)
      }
    })
  }

  // 分享图片
  async shareImage(imagePath, title = '分享图片') {
    try {
      // 保存到相册
      await uni.saveImageToPhotosAlbum({
        filePath: imagePath
      })

      uni.showToast({
        title: '已保存到相册',
        icon: 'success'
      })

      // 尝试调用系统分享
      try {
        await uni.share({
          type: 'image',
          imageUrl: imagePath,
          title: title,
          success: () => {
            console.log('分享成功')
          },
          fail: (error) => {
            console.log('系统分享失败:', error)
          }
        })
      } catch (e) {
        console.log('分享功能不可用:', e)
      }

    } catch (error) {
      console.error('分享图片失败:', error)
      
      if (error.errMsg && error.errMsg.includes('auth deny')) {
        uni.showModal({
          title: '提示',
          content: '需要授权访问相册才能保存图片',
          confirmText: '去设置',
          success: (res) => {
            if (res.confirm) {
              uni.openSetting()
            }
          }
        })
      } else {
        uni.showToast({
          title: '保存失败',
          icon: 'error'
        })
      }
      
      throw error
    }
  }
}

export default ImageShare